<?php

/* * *** 自定义函数集 *** */


function tips($type=0,$msg,$url=''){
	global $cf_user_info;
	if($type=='1'){				//成功提示
		$style = 'uk-text-success';
	}else{						//失败提示
		$style = 'uk-text-danger';
	}
	if($url){
		if($url=='back'){
			$url='javascript:window.history.back()';
		}
	}else{
		if($_SERVER['HTTP_REFERER']){
			$url = $_SERVER['HTTP_REFERER'];
		}
	}
	if($cf_user_info){
		$login='1';	
	}
	require(INC_PATH.'tips.php');
	exit;
}


/**
 * 打印输出,警告框
 * @param string $msg
 * @param string $title
 * @param string $url
 * @param int $time
 * @return string
 */
 //$msg, $model = '0',$title = '信息提示',$target = '', $url = '', $time = 2
 function my_page($msg, $model = '0',$url = '',$target = '',  $time = '2' ,$title = '信息提示' ) {
    $type = 'page';
    require("show_msg.php");
    //my_jump('操作成功','信息提示','http://www.google.com',2);
}
function my_jump($msg, $title = '信息提示', $url = '', $time = 3, $target = '') {
    $type = 'alert';
    require("show_msg.php");
    //my_jump('操作成功','信息提示','http://www.google.com',2);
}

function my_alert($msg, $title = '信息提示', $url = '', $time = 3, $target = '') {
    $type = 'alert';
    require("show_msg.php");
    //my_jump('操作成功','信息提示','http://www.google.com',2);
}

function my_error($msg, $title = '信息提示', $url = '', $time = 5, $target = '') {
    $type = 'error';
    require("show_msg.php");
    //my_jump('操作成功','信息提示','http://www.google.com',2);
}

function my_success($msg, $title = '信息提示', $url = '', $time = 3, $target = '') {
    $type = 'success';
    require("show_msg.php");
    //my_jump('操作成功','信息提示','http://www.google.com',2);
}

function my_warning($msg, $title = '信息提示', $callback = '', $modal = false) {
    $type = 'warning';
    require("show_msg.php");
    //my_jump('操作成功','信息提示','http://www.google.com',2);
}

function my_bigalert($msg, $title = '信息提示', $width = '400', $height = '200', $url = '', $time = 0, $target = '') {
    $type = 'bigalert';
    require("show_msg.php");
    //my_jump('操作成功','信息提示','http://www.google.com',2);
}

function my_close() {
    $type = 'close';
    require("show_msg.php");
}

function my_reload_top() {
    $type = 'reload_top';
    require("show_msg.php");
}

function my_jumpc($msg, $title = '信息提示', $url = '', $time = 0, $target = '') {
    $type = 'jumpc';
    require("show_msg.php");
    //my_jump('操作成功','信息提示','http://www.google.com',2);
}

//直接跳转
function go_url($url) {
    if ($url) {
        header("location:" . $url);
    } else {
        if ($_SERVER['HTTP_REFERER']) {
            header("Location:" . $_SERVER['HTTP_REFERER']);
        }
    }
    exit;
}

/**
 * 打击输出
 * @param array/string $data
 * @return string/array
 */
function dump($data) {

    if ($data!='') {
        echo "<pre>";
        print_r($data);
        //var_dump(debug_backtrace());
        $bt = debug_backtrace();
        if (isset($bt[0])) {
            echo "\n" . $bt[0]['file'] . '  line: ' . $bt[0]['line'];
        }
        echo "</pre>";
    } else {
        echo "null";
    }
    exit;
}



//
function php_error($errno, $errstr, $errfile, $errline) { //错误编号，错误信息，错误文件，错误行号	
    $errortype = array(
        E_ERROR => 'Error',
        E_WARNING => 'Warning',
        E_PARSE => 'Parse',
        E_NOTICE => 'Notice',
        E_STRICT => 'Runtime Notice',
        E_CORE_ERROR => 'Core Error',
        E_CORE_WARNING => 'Core Warning',
        E_COMPILE_ERROR => 'Compile Error',
        E_COMPILE_WARNING => 'Compile Warning',
        E_USER_ERROR => 'User Error',
        E_USER_WARNING => 'User Warning',
        E_USER_NOTICE => 'User Notice'
    );
    echo "<b>$errortype[$errno]: </b> $errstr <br/>\n<b>File ($errline):</b> $errfile <br>\n"; //输出错误信息
}


function get_domain(){
	global $myhost;
	if(strstr($myhost,"192.168.")){				//本地则直接引用ip
		$host = explode(":",$myhost);
		$domain = $host[0];
	}else{
		$array = explode(".",$myhost);
		$count = count($array);
		$domain = '.'.$array[($count-2)].'.'.$array[($count-1)]	;
	}
	return $domain;
}

/**
 * 获取用户ip
 * @return ip
 */
function get_ip() {
    if (isset($_SERVER)) {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $realip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $realip = $_SERVER['HTTP_CLIENT_IP'];
        } else {
            $realip = $_SERVER['REMOTE_ADDR'];
        }
    } else {
        if (getenv("HTTP_X_FORWARDED_FOR")) {
            $realip = getenv("HTTP_X_FORWARDED_FOR");
        } elseif (getenv("HTTP_CLIENT_IP")) {
            $realip = getenv("HTTP_CLIENT_IP");
        } else {
            $realip = getenv("REMOTE_ADDR");
        }
    }
    return $realip;
}

/**
 * 随机码
 * @param int $length
 * @return string $string
 */
function random_code($length = 8,$type='') {
    mt_srand();
    if($type=='NUMBER'){
        $possible_charactors = "0123456789";
    }else{
        $possible_charactors = "abcdefghijkmnpqrstuvwxyz123456789";
    }

    $string = "";
    while(strlen($string)<$length) {
        $string .= substr($possible_charactors,(rand()%(strlen($possible_charactors))),1);
    }
    return $string;
}

/**
 * 写入文件
 * @param string $filename
 * @param string $type
 * @param int $chmod
 */
function write_file($filename, $data, $type = 'php', $chmod = 0777, $write_type = 'w') {
    switch ($type) {
        case "php":
            $header = "<?php\n";
            $footer = "?>";
            break;
        case "js":
            break;
        case "htm":
            break;
        case "log":
            $write_type = 'a';
            break;
        default:
            $header = "<?php\n";
            $footer = "?>";
            break;
    }

    $data = $header . $data . $footer;
    $folder = dirname($filename);
    if (!is_dir($folder))             //大图目录
        mkdir($folder, 0777);
    $handle = fopen($filename, $write_type);
    $result = fwrite($handle, $data);
    fclose($handle);
    @chmod($filename, $chmod);
    if ($result)
        return 1;
    else
        return 0;
}

/**
 * 删除文件
 * @param string $filename
 */
function del_file($filename) {
    if ($filename) {
        if (!stristr($filename, $_SERVER['DOCUMENT_ROOT']))   //限制网站目录内
            die("This file can not delete!");
        if (is_file($filename)) {
            unlink($filename);
        }
    }
}

/**
 * 删除图片
 * @param string $filename
 * @param string $path
 */
function del_photo($photos,$path='') {
    if(!$path){
        $path = UPLOAD_PHOTO;
    }
    if ($photos) {
        $array = explode(',', $photos);
        
        foreach ($array as $photo) {
            $file = $path . $photo;
            $file2 = $path . 'thumb/' . $photo;
            del_file($file);
            del_file($file2);
        }
    }
}

/**
 * 加载相关变量
 * @param string $controller
 * @return array $array	
 */
function load_info_var($controller = '') {
    global $smarty, $cf_info_var;
    if ($controller && $cf_info_var[$controller])
        $info = $cf_info_var[$controller];
    else
        $info = $cf_info_var;
    $smarty->assign('cf_info_var', $info);
}

/**
 * 加载css
 * @param string $css
 * @return smarty info
 */
function load_css($css) {
    global $smarty, $cf_css;
    $file = 'public/css/' . $css . '.css';
    if (is_file(ROOT_PATH . $file)) {
        $cf_css .="\n" . '<link href="' . $file . '" rel="stylesheet" type="text/css" />';
    }
    $smarty->assign('cf_css', $cf_css);
}

/**
 * 加载相关类库
 * @param string $controller
 * @return array $array	
 */
function load_file($file, $path) {
    $file = $path . $file . '.php';
    if (is_file($file)) {
        require_once($file);
        return $file;
    } else {
        echo "加载文件失败  " . $file;
		$bt = debug_backtrace();
        if (isset($bt[0])) {
            echo "<br />" . $bt[0]['file'] . '  line: ' . $bt[0]['line'];
        }
		exit;
    }
}



/**
 * 把二维数组指定键与值生成一维,便于表单处理
 * @param array $data
 * @param string $key_field
 * @param string $value_field
 * @return array $array
 */
function change_array($data, $key_field, $value_field) {
    $array = array();
    if (is_array($data)) {
        foreach ($data as $item) {
            $array[$item[$key_field]] = $item[$value_field];
        }
    }
    return $array;
}

/**
 * 判断验证码
 * @param string $code
 * @return error message 
 */
function check_verify($code) {
    if (!$code) {
        my_jump('请输入验证码!');
    }
    if (strtoupper($code) != $_SESSION["verifycode"]) {
        my_jump('输入的验证码不正确,请重新输入!');
    }
}

/**
 * 判断邮件格式是否正确
 * @param string $mail
 * @return bool
 */
function check_mail($mail) {
    $pattern = "/^[0-9a-z\-\._]{3,}@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/i";
    if (preg_match($pattern, $mail)) {
        return true;
    } else {
        return false;
    }
}

function inputSQL($data) {
    if (!get_magic_quotes_gpc()) {
        return is_array($data) ? array_map('inputSQL', $data) : addslashes($data);
    } else {
        return $data;
    }
}

function outputSQL($data) {
    if (!get_magic_quotes_gpc()) {
        return is_array($data) ? array_map('outputSQL', $data) : stripslashes($data);
    } else {
        return $data;
    }
}

function htmlchar($data) {
    return is_array($data) ? array_map('htmlchar', $data) : htmlspecialchars($data, ENT_QUOTES);
}

function getweek($godate) {
    $week_no = date("w", strtotime($godate));
    switch ($week_no) {
        case 0:
            $week = '日';
            break;
        case 1:
            $week = '一';
            break;
        case 2:
            $week = '二';
            break;
        case 3:
            $week = '三';
            break;
        case 4:
            $week = '四';
            break;
        case 5:
            $week = '五';
            break;
        case 6:
            $week = '六';
            break;
    }
    return $week;
}

//根据id划分目录
function get_cache_folder($id, $set_count = FOLDER_FILE_COUNT) {
    $result = $id - $set_count;
    $count = 1;
    while ($result > 0) {
        $count++;
        $result -=$set_count;
    }
    return $count * $set_count;
}

function add_array_item($add_array, $array) {
    $array1 = array();
	if (is_array($add_array) && is_array($array))
		foreach($array as $k=>$v){
			$array1[$k] = strip_tags($v);	
		}
        $new = $add_array + $array1;
    return $new;
}


function strip_tags_array($array) {    
	if (is_array($array))
		foreach($array as $k=>$v){
			$array[$k] = strip_tags($v);	
	}    
    return $array;
}

function check_contain($str, $find) {

    $str = ',' . trim($str, ',') . ',';
    $find = ',' . trim($find, ',') . ',';
    if ($str && strstr($str, $find)) {
        return true;
    } else {
        return false;
    }
}

//2维数据转成 字符型用,连接
function array_to_string($array, $key, $sep = ',') {
    $str = '';
    if ($array) {
        foreach ($array as $k => $v) {
            $id = $v[$key];
            $str .= $str ? ',' . $id : $id;
        }
    }
    return $str;
}


//获取缩略图地址
function get_thumb_name($img,$pre='thumb'){
	if(strstr($img,".")){
		$pathinfo = pathinfo($img);
		$file = $pathinfo['dirname'].'/'.$pre.$pathinfo['basename'];
		return $file;
	}
}

function get_addr($pro,$city){
	require(INFO_PATH."cf_var_area.php");
	$addr = '';
	if($pro){
		$addr = $cf_var_area[$pro]['title'];
		if($city){
			$addr .=' '.$cf_var_area[$pro]['child'][$city]['title'];
		}
	}
	return $addr;
}

function get_cate($cate1,$cate2){
	require(INFO_PATH."cf_var_cate.php");
	$addr = '';
	if($cate1){
		$cate = $cf_var_cate[$cate1]['title'];
		if($cate2){
			$cate .=' '.$cf_var_cate[$cate1]['child'][$cate2]['title'];
		}
	}
	return $cate;
}
/**
 * hide string
 * @param string $str
 * @param int $from
 * @param int $count
 * @return string 
 */
function hide_code($str,$from='3',$count='3',$sep='*'){
	$len = strlen($str);
	$from = intval($from);
	$count = intval($count);

	if($from<=$len){
		$count = $len-$from>$count ? $count :  $len-$from;
		$pre = substr($str,0,$from);
		$middle = str_repeat($sep,$count);
		$last = substr($str,$from+$count);
		$str = $pre.$middle.$last;
	}
	return $str;
}

/**
 * Put the string into an array
 * @param string $str
 * @param string $prefix
 * @param string $separator
 * @return array 
 */
function my_explode($str,$prefix='',$separator='||'){
	if($str){
		$arr = explode($separator,$str);
		if($prefix){			
			foreach($arr as $k=>$v){
				$pathinfo = pathinfo($v);
				$arr[$k] = $pathinfo['dirname'].'/'.$prefix.$pathinfo['basename'];
			}
		}
	}
	return $arr;				
}
 


/**
 * add myself photo to session
 * @param string $photo
 * @return 
 */
function add_temp_file($file){
	if($file){
		if(strstr($file,",")){						//如果带, 则转成数组添加
			$temp = $_SESSION['user_temp_photo'];
			$file_ary = explode(",",$file);
			if(is_array($temp)){
			}else{
				$temp = array();
			}
			foreach($file_ary as $v){
				
				if(!check_temp_file($v)){			//是否已存在,否则添加
					array_push($temp,$v);
				}
			}
		}else{
			$temp = $_SESSION['user_temp_photo'];
			if(is_array($temp)){
			}else{
				$temp = array();
			}

			if(!check_temp_file($file)){
				array_push($temp,$file);
			}
			
		}
		$_SESSION['user_temp_photo'] = $temp;
	}
}

/**
 * check photo in the session
 * @param string $file
 * @return bool
 */
function check_temp_file($file){
	$temp = $_SESSION['user_temp_photo'];
	if(is_array($temp)){
		if(in_array($file,$temp)){
			return true;
		}else{
			return false;	
		}
	}else{
		return false;	
	}
	
	
}

/**
 * add all temp file
 * @param string $file
 * @return 
 */
function add_all_temp_file($row){
	if(is_array($row)){
		foreach($row as $v){
			if(strstr($v,'/upload/'))	{
				add_temp_file($v);
			}
		}
	}
}




/**
 * 随机获取奖品
 * @param $prize_arr    奖品数组
 * @return array        奖品
 */
function rand_prize($prize_arr){
    $prize_pool=array();
    foreach($prize_arr as $k=>$v){
        $prize_pool += array_fill(count($prize_pool),$v['probability'],$k);
    }
    shuffle($prize_pool);
    $key = array_rand($prize_pool);
    $result = $prize_arr[$prize_pool[$key]];
    return $result;
}

function clean_null($data){
	return is_array($data) ? array_map('clean_null', $data) : trim($data);
	
}

/**
 * 生成二维码
 * @param $prize_arr    奖品数组
 * @return array        奖品
 */

function create_qrcode($value, $outfile = false,$add_logo=false,$logo_file='', $level = 'Q', $size = 5, $margin = 2, $saveandprint=false){
    load_file('qrlib',LIB_PATH . 'phpqrcode/');
    $result = QRcode::png($value, $outfile, $level, $size, $margin);
    //在二维码中间加入logo
    if($add_logo){
        $QR = imagecreatefromstring(file_get_contents($outfile));
        $logo = imagecreatefromstring(file_get_contents($logo_file));
        $QR_width = imagesx($QR);
        $QR_height = imagesy($QR);
        $logo_width = imagesx($logo);
        $logo_height = imagesy($logo);
        $logo_qr_width = $QR_width / 5;
        $scale = $logo_width / $logo_qr_width;
        $logo_qr_height = $logo_height / $scale;
        $from_width = ($QR_width - $logo_qr_width) / 2;
        imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height);
        unlink($outfile);
        $result = imagepng($QR,$outfile);
    }
    return $result;
}

function get_file_size($file) {
	if(is_file($file)){
		 $filesize = filesize($file);
		 if($filesize >= 1073741824) {
			$filesize = round($filesize / 1073741824 * 100) / 100 . ' G';
		 } elseif($filesize >= 1048576) {
			$filesize = round($filesize / 1048576 * 100) / 100 . ' M';
		 } elseif($filesize >= 1024) {
			$filesize = round($filesize / 1024 * 100) / 100 . ' K';
		 } else {
			$filesize = $filesize . ' B';
		 }
		 return $filesize;
	}
}

function check_submit(){
	$SN = $_SERVER['SERVER_NAME'];
	if (substr($_SERVER['HTTP_REFERER'], 7, strlen($SN)) != $SN){
		  return true;//非法的跨域提交
	}else{
		  return false;//正常的提交
	} 
		
}

function now_time(){
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}
function runtime($starttime){    
	return number_format((now_time() - $starttime)*1000, 4).'ms';
}

/**
 *
 * 把对象转成数组
 * @param $object 要转的对象$object
 */
function object_to_array($object){      
    $result = array();      
    $object = is_object($object) ? get_object_vars($object) : $object;      
    foreach ($object as $key => $val){         
        $val = (is_object($val) || is_array($val)) ? object_to_array($val) : $val;         
        $result[$key] = $val; 
    }      
    return $result; 
}

function is_from_app(){
	$agent = $_SERVER['HTTP_USER_AGENT'];
	//echo $agent."<br/>";
	if(strstr($agent,"coship-android")){
		return 'android';	
	}elseif(strstr($_SERVER['HTTP_COSHIP'],"coship-iphone")){
		return 'iphone';	
	}else{
		return false;	
	}
}

//如果历史上一页面相同则用window.history.back
function check_goback($url){
	$back_url = $_SERVER['HTTP_REFERER'];
	if($back_url){
		$back_url = strstr($back_url,".htm") ? $back_url : $back_url.'index.htm';
		if(strstr($back_url,$url)){
			return "javascript:window.history.back()";	
		}else{
			return $url;	
		}
	}else{
		return $url;		
	}
	
	
}

function loop_data($parent_id=0,$data,$pidkey,$idkey,$keyindex='1'){
	$array=array();
	$new_array=array();
	for($i=0;$i<count($data);$i++){
		if($data[$i][$pidkey] == $parent_id){
			$new_array = $data[$i];
			
			$new_array['child'] = loop_data($data[$i][$idkey],$data,$pidkey,$idkey,$keyindex);
			if(empty($new_array['child']))
				unset($new_array['child']);
			//$key = 'id'.$data[$i]['menu_id'];
			if($keyindex){						//是否用key做索引
				$key = $data[$i][$idkey];
				$array[$key] = $new_array;
			}else{
				$array[] = $new_array;
			}
		}
	}
	return $array;
} 


function set_cookie($key,$array,$time='604800'){
	$value = addslashes(serialize($array));
	$domain =get_domain();
	setcookie($key,$value,time()+$time,"/",$domain);
}

function get_cookie($key,$reverse=true){
	
	$value = unserialize(stripslashes($_COOKIE[$key]));	
	$cookie = $_COOKIE[$key] ? unserialize(stripslashes($_COOKIE[$key])) : '';
	if($reverse){									//顺序反向
		$cookie=array_reverse($cookie,$reverse);
	}

	return $cookie;
}

// 正则表达式提取图片地址
function get_image_url($str){
	$str = htmlspecialchars_decode($str);
	$pattern="/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg]))[\'|\"].*?[\/]?>/"; 
	preg_match_all($pattern,$str,$match);
	return $match[1];
		
}

//计算时间的多少秒、多少天
function format_date($time){
    $t=time()-$time;
    $f=array(
        '31536000'=>'年',
        '2592000'=>'个月',
        '604800'=>'星期',
        '86400'=>'天',
        '3600'=>'小时',
        '60'=>'分钟',
        '1'=>'秒'
    );
    foreach ($f as $k=>$v)    {
        if (0 !=$c=floor($t/(int)$k)) {
            return $c.$v.'前';
        }
    }
}

function is_mobile(){  
 $_SERVER['ALL_HTTP'] = isset($_SERVER['ALL_HTTP']) ? $_SERVER['ALL_HTTP'] : '';  
 $mobile_browser = '0';  
 if(preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|iphone|ipad|ipod|android|xoom|playbook|bb10|nokia)/i', strtolower($_SERVER['HTTP_USER_AGENT'])))  
  $mobile_browser++;  
 if((isset($_SERVER['HTTP_ACCEPT'])) and (strpos(strtolower($_SERVER['HTTP_ACCEPT']),'application/vnd.wap.xhtml+xml') !== false))  
  $mobile_browser++;  
 if(isset($_SERVER['HTTP_X_WAP_PROFILE']))  
  $mobile_browser++;  
 if(isset($_SERVER['HTTP_PROFILE']))  
  $mobile_browser++;  
 $mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'],0,4));  
 $mobile_agents = array(  
    'w3c ','acs-','alav','alca','amoi','audi','avan','benq','bird','blac',  
    'blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno',  
    'ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-',  
    'maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-',  
    'newt','noki','oper','palm','pana','pant','phil','play','port','prox',  
    'qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar',  
    'sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-',  
    'tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp',  
    'wapr','webc','winw','winw','xda','xda-'
    );  
 if(in_array($mobile_ua, $mobile_agents))  
  $mobile_browser++;  
 if(strpos(strtolower($_SERVER['ALL_HTTP']), 'operamini') !== false)  
  $mobile_browser++;  
 // Pre-final check to reset everything if the user is on Windows  
 //if(strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows') !== false)  正式上线接触屏蔽
  //$mobile_browser=0;  
 // But WP7 is also Windows, with a slightly different characteristic  
 if(strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows phone') !== false)  
  $mobile_browser++;  
 if($mobile_browser>0)  
  return true;  
 else
  return false;  
}

//curl函数 
function curlOpen($url,$cfg=''){
	$ch = curl_init();	
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_HEADER, 0);	
	if($cfg['ssl']){
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    }
	if($cfg['post']){
		curl_setopt ($ch, CURLOPT_POST, 1);
		curl_setopt ($ch, CURLOPT_POSTFIELDS, $cfg['post']);		
	}
	$result = curl_exec($ch);	
	curl_close($ch);
	return $result;
}

?>